<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016-09-27
 * Time: 13:22
 */

namespace iBrand\Shop\Server\Http\Controllers;

use Carbon\Carbon;
use iBrand\Server\Http\Controllers\Controller;
use iBrand\Component\Category\Models\Category;
use iBrand\Component\Discount\Services\DiscountService;
use iBrand\Component\Order\Models\Comment;
use iBrand\Component\Product\Models\Attribute;
use iBrand\Component\Product\Models\Specification;
use iBrand\Component\Product\Repositories\GoodsRepository;
use iBrand\Component\Product\Repositories\ProductRepository;
use iBrand\Server\Transformers\CommentTransformer;
use iBrand\Server\Transformers\GoodsTransformer;
use iBrand\Component\Discount\Repositories\CouponRepository;
use DB;
use iBrand\Shop\Core\Repositories\O2oGoodsRepository;
use iBrand\Shop\Server\Service\GoodsService;
use iBrand\Shop\Server\Transformers\O2oGoodsTransformer;
use iBrand\TNF\Core\Models\Staff;
use Illuminate\Support\Collection;
use iBrand\Store\Backend\Repositories\GoodsLimitRepository;
use iBrand\Store\Backend\Repositories\GoodsUserLimitRepository;
use iBrand\Server\Repositories\GoodsRemindRepository;
use iBrand\Component\Suit\Repositories\SuitRepository;
use Illuminate\Http\Request;
use iBrand\Component\Seckill\Repositories\SeckillItemRepository;
use iBrand\Component\Seckill\Models\SeckillItem;

class GoodsController extends Controller
{
    protected $goodsRepository;
    protected $couponRepository;
    protected $productRepository;
    protected $discountService;
    protected $Specs;
    protected $suitRepository;

    protected $goodsLimit;
    protected $goodsUserLimit;

    protected $goodsRemind;
    protected $seckillItemRepository;
    protected $o2oGoodsRepository;
    protected $goodsService;

    public function __construct(GoodsRepository $goodsRepository,
                                CouponRepository $couponRepository,
                                ProductRepository $productRepository,
                                DiscountService $discountService,
                                Specification $specification,
                                SuitRepository $suitRepository,
                                GoodsLimitRepository $goodsLimitRepository,
                                GoodsUserLimitRepository $goodsUserLimitRepository,
                                GoodsRemindRepository $goodsRemindRepository,
                                SeckillItemRepository $seckillItemRepository,
                                O2oGoodsRepository $o2oGoodsRepository,
                                GoodsService $goodsService

    )

    {
        $this->goodsRepository = $goodsRepository;
        $this->couponRepository = $couponRepository;
        $this->productRepository = $productRepository;
        $this->discountService = $discountService;
        $this->Specs = $specification;
        $this->suitRepository = $suitRepository;
        $this->goodsLimit = $goodsLimitRepository;
        $this->goodsUserLimit = $goodsUserLimitRepository;
        $this->goodsRemind = $goodsRemindRepository;
        $this->seckillItemRepository = $seckillItemRepository;
        $this->o2oGoodsRepository = $o2oGoodsRepository;
        $this->goodsService = $goodsService;
    }

    public function index()
    {

        //1. get sort parameter
        $orderBy = request('orderBy') ? request('orderBy') : 'created_at';
        $sort = request('sort') ? request('sort') : 'desc';
        $shop_id = request('shop_id');
        $hasFlag = false;
        $goodIds = [];

        //5. get goods list
        $goodsList = $this->goodsRepository->scopeQuery(function ($query) use ($goodIds, $hasFlag, $shop_id) {
            if (!empty($goodIds) OR $hasFlag) {
                $query = $query->whereIn('id', $goodIds);
            }

            if (!empty(request('brand_id'))) {
                $query->where('brand_id', request('brand_id'));
            }

            if (!empty(request('price'))) {
                list($min, $max) = explode('-', request('price'));
                $query = $query->where('sell_price', '>=', $min);
                $query = $query->where('sell_price', '<=', $max);
            }

            if (!empty($keyword = request('keyword'))) {
                $query = $query->where(function ($query) use ($keyword) {
                    $query->where('name', 'like', '%' . $keyword . '%')->orWhere('tags', 'like', '%' . $keyword . '%');
                });
            }


            $query = $query->whereHas('o2oGoods', function ($query) use ($shop_id) {
                $query->where('shop_id', $shop_id)->where('status', 1);
            });

            //return $query->where(['is_largess' => request('is_largess') ? request('is_largess') : 0]);
            return $query;
        })->orderBy($orderBy, $sort)->paginate(16);

        $filters = [];

        return $this->response()->paginator($goodsList, new GoodsTransformer('list'))->setMeta(['filter' => $filters]);
    }

    private function generateFilterConditions()
    {
        //如果是分类页面进入，则需要获取分类下所有商品的模型ID
        if ($categoryId = request('c_id')) {
            $categoryIds = Category::getIdsByParentID($categoryId);
            $categoryGoodsIds = DB::table('el_goods_category')->whereIn('category_id', $categoryIds)->select('goods_id')->distinct()->get()
                ->pluck('goods_id')->toArray();

            $modelIds = $this->goodsRepository->findWhereIn('id', $categoryGoodsIds, ['model_id'])->pluck('model_id')->unique()->toArray();

            $getAttrList = Attribute::ofModelIds($modelIds)->get();

            $attrFilterID = DB::table('el_goods_attribute_relation')->whereIn('goods_id', $categoryGoodsIds)->select('attribute_value_id')->distinct()->get()->pluck('attribute_value_id')->toArray();

            foreach ($getAttrList as $item) {
                $AttributeValue = $item->values->whereIn('id', $attrFilterID);
                foreach ($AttributeValue as $kitem) {
                    $attrArray[$item->name][$kitem->id] = $kitem->name;
                }
            }

            $attrArray = !isset($attrArray) ? [] : $attrArray;

            $attrFilters = ['attr' => ['keys' => array_keys($attrArray), 'values' => $attrArray]];

            $specArray = [];
            $getSpecList = $this->Specs->with('values')->get();

            $SizeFilterID = DB::table('el_goods_spec_relation')->whereIn('el_goods_spec_relation.goods_id', $categoryGoodsIds)->select('spec_value_id')->distinct()->get()->pluck('spec_value_id')->toArray();
            foreach ($getSpecList as $item) {
                $alias = $item->type == 2 ? 'color' : 'size';
                $specValue = $item->values->whereIn('id', $SizeFilterID);
                foreach ($specValue as $kitem) {
                    /*$specArray[$item->name][$kitem->id] = $kitem->name;*/
                    $itemName = $item->name . ':' . $alias;

                    if ($kitem->color) {
                        if (!isset($specArray[$itemName]) OR
                            (isset($specArray[$itemName]) AND !in_array($kitem->color, $specArray[$itemName]))
                        ) {
                            $specArray[$itemName][$kitem->color] = $kitem->color;
                        }
                    } else {
                        $specArray[$itemName][$kitem->id] = $kitem->name;
                    }
                }
            }

            $specArray = !isset($specArray) ? [] : $specArray;
            $specFilters = ['specs' => ['keys' => array_keys($specArray), 'values' => $specArray]];

            return array_merge($attrFilters, $specFilters);
        }

        return [];
    }

    private function getAttributeValueGoodsIds($goodIds, &$hasFlag)
    {
        $attrGoodsIds = $goodIds;
        if (request('attrValue') AND $attrArray = array_unique(request('attrValue'))) {
            foreach ($attrArray as $key => $value) {
                /*if (empty($key)) {*/
                /*$attributesIds = DB::table('el_goods_attribute_value')->where('name',$value)->get()->pluck('id')->toArray();
                $tempAttrIds[$value] = DB::table('el_goods_attribute_relation')->whereIn('attribute_value_id',$attributesIds)->select('goods_id')->distinct()->get()->pluck('goods_id')->toArray();*/
                $tempAttrIds[$value] = DB::table('el_goods_attribute_relation')
                    ->where('attribute_value', 'like', '%' . $value . '%')
                    ->select('goods_id')
                    ->distinct()->get()->pluck('goods_id')->toArray();
                /*} else {
                    $tempAttrIds[$key] = DB::table('el_goods_attribute_relation')->where('attribute_id', $key)->where('attribute_value', $value)->select('goods_id')->distinct()->get()->pluck('goods_id')->toArray();
                }*/
            }

            if (!empty($tempAttrIds)) {
                $attrGoodsIds = empty($attrGoodsIds) ? array_first($tempAttrIds) : $attrGoodsIds;
                foreach ($tempAttrIds as $key => $value) {
                    $attrGoodsIds = array_intersect($attrGoodsIds, $value);
                }
            }

            $hasFlag = true;
        }

        return $attrGoodsIds;
    }

    /**
     * 云货架获取商品数据
     * @return \Dingo\Api\Http\Response
     */
    public function getGoodsList()
    {
        $orderBy = request('orderBy') ? request('orderBy') : 'created_at';
        $sort = request('sort') ? request('sort') : 'desc';
        $categoryGoodsIds = [];

        if ($categoryId = request('c_id')) {
            $categoryIds = [];
            if (str_contains($categoryId, ',')) {
                $paramCategories = explode(',', $categoryId);
                foreach ($paramCategories as $paramCategory) {
                    $categoryIds = array_merge($categoryIds, Category::getIdsByParentID($paramCategory));
                }
            } else {
                $categoryIds = Category::getIdsByParentID($categoryId);
            }
            $categoryGoodsIds = DB::table('el_goods_category')->whereIn('category_id', $categoryIds)->select('goods_id')->distinct()->get()
                ->pluck('goods_id')->toArray();
        }

        $goodsList = $this->o2oGoodsRepository->scopeQuery(function ($query) use ($categoryGoodsIds) {
            $query = $query->where('shop_id', request('shop_id'))->where('status', 1);

            if (count($categoryGoodsIds)) {
                $query = $query->whereIn('goods_id', $categoryGoodsIds);
            }

            if (!empty($keyword = request('keyword'))) {
                $query = $query->whereHas('goods', function ($query) use ($keyword) {
                    $query->where('name', 'like', '%' . $keyword . '%')->orWhere('tags', 'like', '%' . $keyword . '%');
                });
            }

            return $query;
        })->with('goods')->orderBy($orderBy, $sort)->paginate(16);

        return $this->response()->paginator($goodsList, new O2oGoodsTransformer());
    }

    /**
     * 导购下单选择sku
     * @param $id
     * @return \Dingo\Api\Http\Response
     */
    public function edit($id)
    {
        $data = $this->goodsService->getStockByGoodsID($id);
        return $this->api([
            'specs' => $data['specs'],
            'stores' => $data['stores']
        ]);
    }

    public function getDiscountTags($discounts)
    {
        $tagCollection = new Collection();

        if ($discounts instanceof Collection) {
            $discounts->each(function ($item, $key) use ($tagCollection) {
                /*if (!empty($item->tags)) {
                    $tags = explode(",", $item->tags);
                    foreach ($tags as $tag) {
                        $tagCollection->push($tag);
                    }
                }*/
                $tagCollection->push($item->coupon_based == 1 ? '券' : '促');
            });
        }

        return $tagCollection->unique();
    }
}
